#!/bin/bash

if ${__include_sh__:-false}; then
    return
else
    __include_sh__=true
fi

declare -A include_maps
include_maps["include.sh"]=0
include_counter=1

function include()
{
    luwh::push_setting errexit
    luwh::enable_setting errexit
    if [ "${include_maps[$1]}" = "" ]; then
        include_maps[$1]="$((include_counter++))"
        source $(dirname $(which include.sh))/$1
    fi
    luwh::pop_setting
}

function luwh::is_setting()
{
    local origin=$(set -o | grep "^xtrace")
    set +o xtrace

    local result
    if result=$(set -o | egrep "^$1 "); then
        [[ "$result" =~ (on$) ]]
        result="$?"
    else
        echo "is_setting: no such setting: $1"
        exit 1
    fi

    if [[ "$origin" =~ (on$) ]]; then
        set -o xtrace
    fi

    return $result
}

function luwh::enable_setting()
{
    set -o $1
}

function luwh::disable_setting()
{
    set +o $1
}

setting_stack=()
function luwh::push_setting()
{
    local setting
    if luwh::is_setting $1; then
        setting="luwh::enable_setting $1"
    else
        setting="luwh::disable_setting $1"
    fi

    setting_stack[${#setting_stack[*]}]="$setting"
}

function luwh::pop_setting()
{
    ${setting_stack[$((${#setting_stack[*]} - 1))]}
    unset setting_stack[$((${#setting_stack[*]} - 1))]
}

function luwh::assert()
{
    local left="$1"
    local operator="$2"
    local right="$3"
    local message="$4"
    if ! [ "$left" "$operator" "$right" ]; then
        floge "$message" || echo "$message"
        exit 3
    fi
}
